package cn.qin.xhangapi.util.auth;

import cn.qin.xhangapi.pojo.SysMenu;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 系统用户权限菜单工具类
 *
 * @author 多仔ヾ
 */
public class SysMenuUtil {
    private static List<SysMenu> allMenuList = null;
    private static Map<String, SysMenu> allMenuMap = null;

    /**
     * 构建树形权限菜单
     *
     * @author 多仔ヾ
     * @param list 系统用户权限菜单列表
     * @return java.util.List<SysMenu>
     */
    public static List<SysMenu> buildTreeMenu(List<SysMenu> list) {
        allMenuList = new ArrayList<>(list);
        List<SysMenu> roots = new ArrayList<>();
        for (SysMenu sysMenu : list) {
            if (sysMenu.getParentId() == -1) {
                roots.add(sysMenu);
            }
        }
        allMenuList.removeAll(roots);
        for (SysMenu sysMenu : roots) {
            sysMenu.setChildren(getChildren(sysMenu));
        }
        return roots;
    }

    /**
     * 根据父权限菜单获取子权限菜单
     *
     * @author 多仔ヾ
     * @param parent 父权限菜单
     * @return java.util.List<SysMenu>
     */
    private static List<SysMenu> getChildren(SysMenu parent) {
        List<SysMenu> childrenList = parent.getChildren() == null ? new ArrayList<>() : parent.getChildren();
        for (SysMenu sysMenu : allMenuList) {
            if (parent.getId().equals(sysMenu.getParentId())) {
                childrenList.add(sysMenu);
            }
        }
        allMenuList.removeAll(childrenList);
        for (SysMenu sysMenu : childrenList) {
            sysMenu.setChildren(getChildren(sysMenu));
        }
        return childrenList;
    }

}